import React,{useRef,useState} from "react";
import { Typography, Select, Grid,TextField, Button, Checkbox, MenuItem } from "@material-ui/core";
import SystemMessageBox from "@components/SystemMessage/SystemMessageBox"
import SystemMessageInfo from "@components/SystemMessage/SystemMessageInfo";

import {callGetMessages} from "@components/SystemMessage/SystemMessageServiceAsync";
import SystemMessage from "@components/SystemMessage/SystemMessage";

const messageMap=new Map();

const SystemMessageGlobalSetting=SystemMessage.globalSetting;
const SystemMessageConst=SystemMessage.const;


export default function MsgCodeTester() {

  const systemMessageBoxRef=useRef();
  const systemMessageInfoRef=useRef();

  const UserSeveritys=["INFO","QUESTION","WARNING","ERROR"];
  
  const [showPrintButton,setShowPrintButton]=useState(SystemMessageGlobalSetting.printEnabled);
  const [isChineseMessage,setIsChineseMessage]=useState(SystemMessageGlobalSetting.language==="chi");
  const [showMessageCode,setShowMessageCode]=useState(SystemMessageGlobalSetting.codeVisible);
  const [isInfoMessageModal,setIsInfoMessageModal]=useState(SystemMessageGlobalSetting.isInfoMessageModal);
  
  const [override,setOverride]=useState(false);
  const [messageLevel,setMessageLevel]=useState("0");
  const [listOfMessageLevel,setListOfMessageLevel]=useState("0,1");

  const [userSeverity,setUserSeverity]=useState(UserSeveritys[0]);
  const [userInputTitle,setUserInputTitle]=useState("Testing Title");
  const [userInputDescription,setUserInputDescription]=useState("Testing Description");
  const [userInputCause,setUserInputCause]=useState("Testing Cause");
  const [userInputAction,setUserInputAction]=useState("Testing Action");

  const [confirmButtonText,setConfirmButtonText]=useState("OK");
  const [printButtonText,setPrintButtonText]=useState("Print Message");

  const [substituted,setSubstituted]=useState("%1");
  const [substitution,setSubstitution]=useState("test1");

  const [horizontal,setHorizontal]=useState(SystemMessageGlobalSetting.horizontal);
  const [vertical,setVertical]=useState(SystemMessageGlobalSetting.vertical);  
  const [autoHideDuration,setAutoHideDuration]=useState(SystemMessageGlobalSetting.autoHideDuration);

  const [messageCode0,setMessageCode0]=useState("00003-W-009");
  const [messageCode1,setMessageCode1]=useState("00003-W-011");
  
  const formatMessage=(message)=>{
       var ret={...message};
       var substituteds=substituted.split(",");
       var substitutions=substitution.split(",");
       for(var i=0;i<substituteds.length&&i<substitutions.length;i++){
          var substitutedi=substituteds[i];
          var substitutioni=substitutions[i];
          ret["engMessageHeader"]=ret["engMessageHeader"].replace(substitutedi,substitutioni);
          ret["chiMessageHeader"]=ret["chiMessageHeader"].replace(substitutedi,substitutioni);
          ret["engDescription"]=ret["engDescription"].replace(substitutedi,substitutioni);
          ret["chiDescription"]=ret["chiDescription"].replace(substitutedi,substitutioni);
          ret["engCause"]=ret["engCause"].replace(substitutedi,substitutioni);
          ret["chiCause"]=ret["chiCause"].replace(substitutedi,substitutioni);
          ret["engAction"]=ret["engAction"].replace(substitutedi,substitutioni);
          ret["chiAction"]=ret["chiAction"].replace(substitutedi,substitutioni);
       }
       
       return ret;
  };

  return (
    <div className="App">
      
        <Typography variant="h6">System Message Library Testing</Typography>
        <fieldset>
            <legend>Library Setting</legend>
            <Grid container spacing={2}>
              <Grid item xs={3}>Show Print Button ?</Grid>
              <Grid item xs={3}><Checkbox checked={showPrintButton} onMouseDown={()=>{ 
                 setShowPrintButton(!showPrintButton) 
                 }} ></Checkbox></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                  onClick={()=>{
                        SystemMessageGlobalSetting.horizontal=horizontal;
                        SystemMessageGlobalSetting.vertical=vertical;
                        SystemMessageGlobalSetting.autoHideDuration=autoHideDuration;
                        SystemMessageGlobalSetting.isInfoMessageModal=isInfoMessageModal;
                        SystemMessageGlobalSetting.confirmButtonText=confirmButtonText;
                        SystemMessageGlobalSetting.printButtonText=printButtonText;
                        systemMessageBoxRef.current.alert("Information","Setting is saved.","","")
                  }}
              >Save Global Setting</Button></Grid>
              <Grid item xs={3}><Button variant="outlined"
                   onClick={()=>{
                     var desc="";
                     for(var key in SystemMessageGlobalSetting){
                        var value=SystemMessageGlobalSetting[key];
                        desc+=key+"="+value+"<br/>";
                     }
                     systemMessageBoxRef.current.alert("Information",desc,"","")
               }}
              >Get Current Setting</Button></Grid>

              <Grid item xs={3}>Mask parent application (for Info Msg only)?</Grid>
              <Grid item xs={3}><Checkbox checked={isInfoMessageModal} onMouseDown={()=>{ setIsInfoMessageModal(!isInfoMessageModal) }}></Checkbox></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}></Grid>

              <Grid item xs={3}>Info AutoHideDuration:</Grid>
              <Grid item xs={3}><TextField value={autoHideDuration} onChange={(e)=>{ setAutoHideDuration(e.target.value) }} ></TextField></Grid>
              <Grid item xs={3}>Info Position:</Grid>
              <Grid item xs={3}>
                 <Select value={horizontal} onChange={(e)=>{setHorizontal(e.target.value)}}>
                     <MenuItem value={SystemMessageConst.HORIZONTAL_LEFT} key={SystemMessageConst.HORIZONTAL_LEFT}>{SystemMessageConst.HORIZONTAL_LEFT}</MenuItem>
                      <MenuItem value={SystemMessageConst.HORIZONTAL_CENTER} key={SystemMessageConst.HORIZONTAL_CENTER}>{SystemMessageConst.HORIZONTAL_CENTER}</MenuItem>
                      <MenuItem value={SystemMessageConst.HORIZONTAL_RIGHT} key={SystemMessageConst.HORIZONTAL_RIGHT}>{SystemMessageConst.HORIZONTAL_RIGHT}</MenuItem>
                      
                 </Select> -
                 <Select value={vertical} onChange={(e)=>{setVertical(e.target.value)}}>
                      <MenuItem value={SystemMessageConst.VERTICAL_TOP} key={SystemMessageConst.VERTICAL_TOP}>{SystemMessageConst.VERTICAL_TOP}</MenuItem>
                      <MenuItem value={SystemMessageConst.VERTICAL_MIDDLE} key={SystemMessageConst.VERTICAL_MIDDLE}>{SystemMessageConst.VERTICAL_MIDDLE}</MenuItem>
                      <MenuItem value={SystemMessageConst.VERTICAL_BOTTOM} key={SystemMessageConst.VERTICAL_BOTTOM}>{SystemMessageConst.VERTICAL_BOTTOM}</MenuItem>
                      
                 </Select>
              </Grid>

              <Grid item xs={3}>Box Confirm Button Text:</Grid>
              <Grid item xs={3}><TextField value={confirmButtonText} onChange={(e)=>{ setConfirmButtonText(e.target.value) }}  ></TextField></Grid>
              <Grid item xs={3}>Box Print Button Text:</Grid>
              <Grid item xs={3}><TextField value={printButtonText} onChange={(e)=>{ setPrintButtonText(e.target.value) }}  ></TextField></Grid>


            </Grid>
        </fieldset>
        <fieldset>
            <legend>Initialization</legend>
            <Grid container spacing={2}>
              <Grid item xs={3}>Message Level:</Grid>
              <Grid item xs={3}><TextField value={messageLevel} onChange={(e)=>{ setMessageLevel(e.target.value) }} ></TextField></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                onClick={()=>{
                   var payload={
                     messageLevel:messageLevel
                   };
                   callGetMessages(payload).then((res)=>{
                      var messages=res["data"]["self"];
                      for(var i=0;i<messages.length;i++){
                         var message=messages[i];
                         var key=message["functionId"]+"-"+message["severityCode"]+"-"+message["messageCode"];
                         messageMap.set(key,message);
                      }
                      systemMessageBoxRef.current.info("Information","System Message Init result: true, No. of level(s) loaded: " + messages.length,"","");
                   });
                }}
              >Load Message By Level</Button></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                 onClick={()=>{
                   messageMap.clear();
                   systemMessageBoxRef.current.info("Information","Message is cleaned.","","");
                 }}
              >Clean up Message</Button></Grid>

              
            </Grid>
        </fieldset>
        <fieldset>
            <legend>Show Message Box</legend>
            <Grid container spacing={2}>
              <Grid item xs={3}>Message Code:</Grid>
              <Grid item xs={3}><TextField value={messageCode0} onChange={(e)=>{ setMessageCode0(e.target.value); }} ></TextField></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                  onClick={()=>{
                     var message=messageMap.get(messageCode0);
                     if(message==null){
                        systemMessageBoxRef.current.error("ERROR","No message for the provided message code. Null object is returned","","");
                        return;
                     }
                     if(override){
                        message["engMessageHeader"]=message["chiMessageHeader"]=userInputTitle;
                        message["engDescription"]=message["chiDescription"]=userInputDescription;
                        message["engCause"]=message["chiCause"]=userInputCause;
                        message["engAction"]=message["chiAction"]=userInputAction;
                     }
                     message=formatMessage(message);
                     switch (userSeverity){
                        case UserSeveritys[0]:  
                           systemMessageBoxRef.current.infoMessage(message);
                           break;
                        case UserSeveritys[1]:  
                           systemMessageBoxRef.current.confirmMessage(message);
                           break;
                        case UserSeveritys[2]:  
                           systemMessageBoxRef.current.alertMessage(message);
                           break;
                        case UserSeveritys[3]:  
                           systemMessageBoxRef.current.errorMessage(message);
                           break;
                        default:break;
                      }
                  }}
              >Show Message Box By Code</Button></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                onClick={()=>{
                  var message=messageMap.get(messageCode0);
                  if(message==null){
                     systemMessageInfoRef.current.error("ERROR","No message for the provided message code. Null object is returned","","");
                     return;
                  }
                  if(override){
                     message["engMessageHeader"]=message["chiMessageHeader"]=userInputTitle;
                     message["engDescription"]=message["chiDescription"]=userInputDescription;
                     message["engCause"]=message["chiCause"]=userInputCause;
                     message["engAction"]=message["chiAction"]=userInputAction;
                  }
                  message=formatMessage(message);
                  switch (userSeverity){
                     case UserSeveritys[0]:  
                        systemMessageInfoRef.current.infoMessage(message);
                        break;
                     case UserSeveritys[1]:  
                        systemMessageInfoRef.current.confirmMessage(message);
                        break;
                     case UserSeveritys[2]:  
                        systemMessageInfoRef.current.alertMessage(message);
                        break;
                     case UserSeveritys[3]:  
                        systemMessageInfoRef.current.errorMessage(message);
                        break;
                     default:break;
                   }
               }}
              >Show Info Message By Code</Button></Grid>

              <Grid item xs={3}>Override by the user input?</Grid>
              <Grid item xs={3}><Checkbox value={override} onMouseDown={()=>{setOverride(!override)}}></Checkbox></Grid>
              <Grid item xs={3}>Chinese Message?<Checkbox checked={isChineseMessage} onMouseDown={()=>{ 
                 setIsChineseMessage(!isChineseMessage) 
                 }} ></Checkbox></Grid>
              <Grid item xs={3}>Show Message Code?<Checkbox checked={showMessageCode} onMouseDown={()=>{ 
                 setShowMessageCode(!showMessageCode) 
                 }}></Checkbox></Grid>

              <Grid item xs={3}>Substituted String:</Grid>
              <Grid item xs={3}><TextField value={substituted} onChange={(e)=>{setSubstituted(e.target.value)}}></TextField></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}></Grid>

              <Grid item xs={3}>Substitution String:</Grid>
              <Grid item xs={3}><TextField value={substitution} onChange={(e)=>{setSubstitution(e.target.value)}}></TextField></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}></Grid>

              <Grid item xs={3}>User Input Title:</Grid>
              <Grid item xs={3}><TextField value={userInputTitle} onChange={(e)=>{ setUserInputTitle(e.target.value) }} ></TextField></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                onClick={()=>{
                     switch (userSeverity){
                       case UserSeveritys[0]:  
                          systemMessageBoxRef.current.info(userInputTitle,userInputDescription,userInputCause,userInputAction);
                          break;
                       case UserSeveritys[1]:  
                          systemMessageBoxRef.current.confirm(userInputTitle,userInputDescription,userInputCause,userInputAction);
                          break;
                       case UserSeveritys[2]:  
                          systemMessageBoxRef.current.alert(userInputTitle,userInputDescription,userInputCause,userInputAction);
                          break;
                       case UserSeveritys[3]:  
                          systemMessageBoxRef.current.error(userInputTitle,userInputDescription,userInputCause,userInputAction);
                          break;
                        default:break;
                     }
                }}
              >Show Message Box By User Input</Button></Grid>
              <Grid item xs={3}><Button variant="outlined" 
                 onClick={()=>{
                  switch (userSeverity){
                    case UserSeveritys[0]:  
                       systemMessageInfoRef.current.info(userInputTitle,userInputDescription);
                       break;
                    case UserSeveritys[1]:  
                       systemMessageInfoRef.current.confirm(userInputTitle,userInputDescription);
                       break;
                    case UserSeveritys[2]:  
                       systemMessageInfoRef.current.alert(userInputTitle,userInputDescription);
                       break;
                    case UserSeveritys[3]:  
                       systemMessageInfoRef.current.error(userInputTitle,userInputDescription);
                       break;
                     default:break;
                  }
             }}
              >Show Info Message By User Input</Button></Grid>

              <Grid item xs={3}>User Input Description:</Grid>
              <Grid item xs={3}><TextField value={userInputDescription} onChange={(e)=>{ setUserInputDescription(e.target.value) }} ></TextField></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}>
                 
              </Grid>

              <Grid item xs={3}>User Input Cause:</Grid>
              <Grid item xs={3}><TextField value={userInputCause} onChange={(e)=>{ setUserInputCause(e.target.value) }} ></TextField></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}>
                 
              </Grid>

              <Grid item xs={3}>User Input Action:</Grid>
              <Grid item xs={3}><TextField value={userInputAction} onChange={(e)=>{ setUserInputAction(e.target.value) }}  ></TextField></Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}></Grid>

              <Grid item xs={3}>User Severity:</Grid>
              <Grid item xs={3}>
                 <Select value={userSeverity} onChange={(e)=>{ setUserSeverity(e.target.value); }}>
                     {UserSeveritys.map(item => <MenuItem value={item} key={item}>{item}</MenuItem>)}
                 </Select>
              </Grid>
              <Grid item xs={3}></Grid>
              <Grid item xs={3}></Grid>

              
            </Grid>
        </fieldset>
        <fieldset>
            <legend>Display By User Input (No Message Box)</legend>
            <Grid container spacing={2}>
              <Grid item xs={3}>
                 Message Code:
              </Grid>
              <Grid item xs={3}>
                 <TextField value={messageCode1} onChange={(e)=>{ setMessageCode1(e.target.value); }} ></TextField>
              </Grid>
              <Grid item xs={3}>
                  <Button variant="outlined"  onClick={e=>{
                     var message=messageMap.get(messageCode0);
                     if(message==null){
                        systemMessageInfoRef.current.error("ERROR","No message for the provided message code. Null object is returned","","");
                        return;
                     }
                     
                     var str = "";
						str += "Description: " + message["engDescription"] +"<br/>";
						str += "Cause: " + message["engCause"] +"<br/>";
						str += "Action: " + message["engAction"] +"<br/>";
						str += "Header: " + message["engMessageHeader"] +"<br/>";
						str += "Button: " + message["engNumOfButton"] + "<br/>";
						str += "Chinese Description: " + message["chiDescription"] +"<br/>";
						str += "Chinese Cause: " + message["chiCause"] +"<br/>";
						str += "Chinese Action: " + message["chiAction"] +"<br/>";							
						str += "Chinese Header: " + message["chiMessageHeader"] +"<br/>";
						str += "Chinese Button: " + message["chiNumOfButton"] + "<br/>";
						
						str += "Effective Date: " + message["effectiveDtm"]+"<br/>";
						str += "Expiry Date: " + message["expiryDtm"] +"<br/>";
						str += "Default Button Index: " + message["defaultButton"] +"<br/>";
						str += "Level: " + message["messageLevel"];

                      var descs=[
                             str
                      ];
                      systemMessageBoxRef.current.alert("Information",descs);
                  }}>Show Message Content By Code</Button>
              </Grid>
              <Grid item xs={3}></Grid>

              <Grid item xs={3}>
                  List of Message Level:
              </Grid>
              <Grid item xs={3}>
                 <TextField value={listOfMessageLevel} onChange={(e)=>{ setListOfMessageLevel(e.target.value); }}></TextField>
              </Grid>
              <Grid item xs={3}>
                  <Button variant="outlined"   onClick={e=>{
                      var payload={
                        messageLevel:listOfMessageLevel
                      };
                      callGetMessages(payload).then((res)=>{
                         var messages=res["data"]["self"];
                         systemMessageBoxRef.current.info("Information","No. of records: " + messages.length,"","");
                      });
                  }}>Show Message Content By Level</Button>
              </Grid>
              <Grid item xs={3}></Grid>
            </Grid>
        </fieldset>
        
      <SystemMessageBox ref={systemMessageBoxRef} printEnabled={showPrintButton} language={isChineseMessage?SystemMessageConst.LANGUAGE_CHI :SystemMessageConst.LANGUAGE_ENG}
         codeVisible={showMessageCode}  confirmButtonText={confirmButtonText} printButtonText={printButtonText}
      ></SystemMessageBox>
      <SystemMessageInfo ref={systemMessageInfoRef} language={isChineseMessage?SystemMessageConst.LANGUAGE_CHI :SystemMessageConst.LANGUAGE_ENG} 
         codeVisible={showMessageCode}   horizontal={horizontal} vertical={vertical}  autoHideDuration={autoHideDuration}
         isInfoMessageModal={isInfoMessageModal}
      ></SystemMessageInfo>
    </div>
  );
}
